package com.chuangke.flowable.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chuangke.admin.data.builder.DeptDataBuilder;
import com.chuangke.admin.data.builder.UserDataBuilder;
import com.chuangke.admin.entity.SysDept;
import com.chuangke.admin.entity.SysRole;
import com.chuangke.admin.entity.SysUser;
import com.chuangke.admin.entity.SysUserAuditDept;
import com.chuangke.admin.service.SysRoleService;
import com.chuangke.admin.service.SysUserAuditDeptService;
import com.chuangke.admin.service.SysUserRoleQueryService;
import com.chuangke.admin.service.SysUserService;
import com.chuangke.common.data.builder.DataBuildConfig;
import com.chuangke.common.data.builder.DataBuilder;
import com.chuangke.common.db.page.CkPageQuery;
import com.chuangke.common.exception.ChuangkeException;
import com.chuangke.common.utils.ExceptionUtil;
import com.chuangke.common.utils.SpringContextUtil;
import com.chuangke.flowable.constant.Consts;
import com.chuangke.flowable.dao.FlowableTaskMapper;
import com.chuangke.flowable.model.FlowableFormModel;
import com.chuangke.flowable.model.FlowableFormViewModel;
import com.chuangke.flowable.model.FlowableHandler;
import com.chuangke.flowable.model.FlowableNode;
import com.chuangke.flowable.service.FlowableService;
import com.chuangke.flowable.service.ImageService;
import com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException;
import org.apache.commons.collections.CollectionUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.engine.HistoryService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Comment;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskInfo;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class FlowableServiceImpl implements FlowableService {

	private static final Logger logger = LoggerFactory.getLogger(FlowableServiceImpl.class);

	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private ProcessEngine processEngine;
	@Autowired
	private HistoryService historyService;

	@Autowired
	private SysUserRoleQueryService sysUserRoleQueryService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysUserAuditDeptService sysUserAuditDeptService;

	@Autowired
	private FlowableTaskMapper flowableTaskMapper;
	
	@Autowired
    private ImageService imageService;

	@Override
	public String startProcessInstance(String processDefinitionKey, FlowableHandler handler,
			FlowableFormModel flowableFormModel, Map<String, Object> variables) {
		variables.put(Consts.VAR_NAME_FORM, JSON.toJSONString(flowableFormModel));
		return startProcessInstance(processDefinitionKey, handler, variables);
	}

	@Override
	public String startProcessInstance(String processDefinitionKey, FlowableHandler handler,
			Map<String, Object> variables) {
		if (StrUtil.isBlank(handler.getDeptId())) {
			throw new ChuangkeException("流程实例未设置组织机构代码");
		}
		variables.put(Consts.VAR_NAME_DEPT, handler.getDeptId());
		Authentication.setAuthenticatedUserId(handler.getUserId());
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey,
				handler.getBusinessKey(), variables);

		return processInstance.getId();
	}

	@Async
	@Override
	public CompletableFuture<Map<String, String>> asyncComplete(FlowableHandler handler, String message,
			Map<String, Object> variables) {
		Map<String, String> result = retryComplete(handler, message, variables);
		return CompletableFuture.completedFuture(result);
	}

	private Map<String, String> retryComplete(FlowableHandler handler, String message, Map<String, Object> variables) {
		Map<String, String> result = new HashMap<>();
		try {
			SpringContextUtil.getBean(FlowableService.class).complete(handler, message, variables);
			result.put("key", handler.getBusinessKey());
			result.put("status", "200");
			handler.setCount(handler.getCount() + 1);
		} catch (Exception e) {
			Throwable ex = ExceptionUtil.getSourceException(e);
			if (ex instanceof MySQLTransactionRollbackException && handler.getCount() < 3) {
				return retryComplete(handler, message, variables);
			} else {
				String err = ex instanceof MySQLTransactionRollbackException ? "处理超时，请重新处理！" : ex.getMessage();
				err = err.startsWith("No outgoing sequence flow of element") ? "当前节点不支持此操作" : err;
				result.put("status", "500");
				result.put("msg", err);
				logger.error("审批失败，{}", e.getMessage());
			}
		}
		return result;
	}

	private List<String> getRoleIdList(List<String> roleNameList) {
		List<SysRole> sysRoleList = sysRoleService.findList();
		return sysRoleList.stream().filter(sysRole -> roleNameList.contains(sysRole.getName())).map(SysRole::getId)
				.collect(Collectors.toList());
	}

	@Override
	public void complete(FlowableHandler handler, String message, Map<String, Object> variables) {
		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
				.processInstanceBusinessKey(handler.getBusinessKey()).singleResult();
		if (processInstance == null) {
			throw new ChuangkeException(String.format("未找到[%s]的流程信息", handler.getBusinessKey()));
		}

		Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
		List<IdentityLink> linkList = taskService.getIdentityLinksForTask(task.getId());
		List<String> roleList = new ArrayList<>();
		for (IdentityLink link : linkList) {
			if ("candidate".equals(link.getType())) {
				roleList.add(link.getGroupId());
			}
		}

		List<String> roleIdList = getRoleIdList(roleList);
		String deptId = (String) taskService.getVariable(task.getId(), "deptId");

		boolean canAudit = false;
		for (String roleId : roleIdList) {
			if (sysUserAuditDeptService.exists(handler.getUserId(), roleId, deptId)) {
				canAudit = true;
				break;
			}
		}

		if (!canAudit) {
			throw new ChuangkeException("没有审批操作权限");
		}

		if (!StrUtil.isBlank(message)) {
			taskService.addComment(task.getId(), processInstance.getId(), message);
		}
		Map<String, Object> localVariables = new HashMap<>();
		localVariables.put(Consts.VAR_NAME_AUDIT_OPT,
				StrUtil.isBlank(handler.getAudit()) ? Consts.VAR_AUDIT_OPT_AGREE : handler.getAudit());
		taskService.setVariablesLocal(task.getId(), localVariables);
		taskService.claim(task.getId(), handler.getUserId());

		variables.putAll(localVariables);
		variables.put("businessKey", handler.getBusinessKey());
		taskService.complete(task.getId(), variables);
	}

	@Override
	public void reject(FlowableHandler handler, String message, Map<String, Object> variables) {
	}

	public void revoke(FlowableHandler handler) {
	}

	@Override
	public List<FlowableNode> getFlowableNodeList(String businessKey) {
		List<HistoricTaskInstance> list = processEngine.getHistoryService() // 历史相关Service
				.createHistoricTaskInstanceQuery() // 创建历史任务实例查询
				.processInstanceBusinessKey(businessKey)
//	            .finished() // 查询已经完成的任务
				.orderByTaskCreateTime().asc().list();

		List<FlowableNode> nodeList = new ArrayList<>();

		if (list == null || list.isEmpty()) {
			return nodeList;
		}

		Map<String, SysUser> userMap = sysUserService.findMap();

		List<HistoricVariableInstance> variableList = getVariableInstance(list.get(0).getProcessInstanceId());
		List<Comment> commentList = taskService.getProcessInstanceComments(list.get(0).getProcessInstanceId());

		FlowableNode flowableNode = null;
		for (HistoricTaskInstance hti : list) {
			flowableNode = new FlowableNode();

			String opt = (String) getVariableValue(variableList, hti.getId(), Consts.VAR_NAME_AUDIT_OPT);
			flowableNode.setState(opt == null ? FlowableNode.STATE_ING : Consts.OPT_STATE_MAP.get(opt));
			flowableNode.setId(hti.getId());
			flowableNode.setProcessInstanceId(hti.getProcessInstanceId());
			flowableNode.setActivityName(hti.getName());

			if (StrUtil.isBlank(hti.getAssignee())) {
				Map<String, Object> map = taskService.getVariables(hti.getId());
				String deptId = (String) map.get(Consts.VAR_NAME_DEPT);
				UserTask userTask = getUserTaskByTask(hti);
				List<String> roleList = userTask.getCandidateGroups();

				List<String> roleIdList = getRoleIdList(roleList);
				List<String> allUserList = new ArrayList<>();
				List<String> allUserNameList = new ArrayList<>();
				for (String role : roleIdList) {
					List<String> userList = findUserByRole(deptId, role);
					if (!CollectionUtils.isEmpty(userList)) {
						allUserList.addAll(userList);
						for (String userId : userList) {
							SysUser user = userMap.get(userId);
							allUserNameList.add(user == null ? userId : user.getNickName());
						}
					} else {
						allUserNameList.add(String.format("流程中未找到角色【%s】对应的审批用户", role));
						logger.error("流程中未找到角色{}的用户", role);
					}
				}
				flowableNode.setAssignee(String.join(",", allUserList));
				flowableNode.setAssigneeName(String.join(",", allUserNameList));
			} else {
				String userId = hti.getAssignee();
				SysUser user = userMap.get(userId);
				flowableNode.setAssignee(userId);
				flowableNode.setAssigneeName(user == null ? userId : user.getNickName());
			}

			flowableNode.setStartTime(hti.getCreateTime());
			flowableNode.setEndTime(hti.getEndTime());
			flowableNode.setComment(getComment(commentList, hti.getId()));

			nodeList.add(flowableNode);
		}
		return nodeList;
	}

	private List<String> findUserByRole(String deptId, String role) {
		List<SysUserAuditDept> list = sysUserAuditDeptService.findUserByRoleDept(role, deptId);
		return list.stream().map(SysUserAuditDept::getUserId).collect(Collectors.toList());
	}

	private UserTask getUserTaskByTask(TaskInfo task) {
		// 获取流程定义信息
		BpmnModel bpmnModel = processEngine.getRepositoryService().getBpmnModel(task.getProcessDefinitionId());
		Process process = bpmnModel.getProcesses().get(0);
		List<UserTask> UserTaskList = process.findFlowElementsOfType(UserTask.class);

		for (UserTask userTask : UserTaskList) {
			if (task.getTaskDefinitionKey().equals(userTask.getId())) {
				return userTask;
			}
		}
		return null;
	}

	private List<HistoricVariableInstance> getVariableInstance(String processInstanceId) {
		return processEngine.getHistoryService().createHistoricVariableInstanceQuery()
				.processInstanceId(processInstanceId).list();
	}

	private String getComment(List<Comment> commentList, String taskId) {
		for (Comment comment : commentList) {
			if (taskId.equals(comment.getTaskId())) {
				return comment.getFullMessage();
			}
		}
		return null;
	}

	private Object getVariableValue(List<HistoricVariableInstance> variableList, String taskId, String variableName) {
		for (HistoricVariableInstance variableInstance : variableList) {
			if (taskId.equals(variableInstance.getTaskId())
					&& variableName.equals(variableInstance.getVariableName())) {
				return variableInstance.getValue();
			}
		}
		return null;
	}

	@Override
	public IPage<FlowableFormViewModel> findTodoTask(CkPageQuery request) {
		// TODO 待优化，可以不用sysUserRoleService，只用sysRoleDeptService
		String userId = (String)request.get("userId") ;
		List<SysRole> userRoleList = sysUserRoleQueryService.findRoleByUserId(userId);

		if (CollectionUtils.isEmpty(userRoleList)) {
			return request.getPage();
		}

		Map<String, List<String>> roleDeptMap = new HashMap<>();

		for (SysRole role : userRoleList) {
			List<SysDept> deptList = sysUserAuditDeptService.findUserDeptWithChildren(userId,
					role.getId());
			List<String> deptIdList = deptList.stream().map(SysDept::getId).collect(Collectors.toList());// 部门集合

			if (!CollectionUtils.isEmpty(deptIdList)) {
				roleDeptMap.put(role.getName(), deptIdList);
			}
		}

		if (roleDeptMap.isEmpty()) {
			return request.getPage();
		}

		StringBuilder sql = new StringBuilder();
		sql.append("select distinct ART.ID_ id,ART.CREATE_TIME_,ART.NAME_ name,ARV.TEXT_ text ");//
		sql.append("from ACT_RU_TASK ART,ACT_RU_VARIABLE ARV ");
		sql.append("where ART.PROC_INST_ID_ = ARV.PROC_INST_ID_  and ARV.NAME_='formModel'");
		sql.append("and (");

		int i = 0;
		for (String role : roleDeptMap.keySet()) {
			sql.append("(exists (select 1 from ACT_RU_IDENTITYLINK LINK where LINK.TYPE_ = 'candidate' ");
			sql.append("	and LINK.TASK_ID_ = ART.ID_ and LINK.GROUP_ID_ ='").append(role).append("') ");
			sql.append("and exists(select 1 from ACT_RU_VARIABLE ARV1 where ART.PROC_INST_ID_ = ARV1.PROC_INST_ID_ ");
			sql.append("	and ARV1.NAME_= 'deptId' and ARV1.TEXT_ in (");
			for (int j = 0; j < roleDeptMap.get(role).size(); j++) {
				sql.append("'").append(roleDeptMap.get(role).get(j)).append("'");
				if (j < roleDeptMap.get(role).size() - 1) {
					sql.append(",");
				}
			}
			sql.append(")))");

			i++;
			if (i <= (roleDeptMap.keySet().size() - 1)) {
				sql.append(" or ");
			}
		}
		sql.append(")");
		sql.append("order by ART.CREATE_TIME_ asc");
		// 查询的时候会根据ID_进行组织数据，如果ID_一致，就认为是一条数据

		IPage<Map<String, Object>> pageData = flowableTaskMapper.select(request.getPage(), sql.toString());

		List<FlowableFormViewModel> list = new ArrayList<>();
		for (Map<String, Object> map : pageData.getRecords()) {
			FlowableFormViewModel flowableFormModel = StrUtil.isBlank((String) map.get("text"))
					? new FlowableFormViewModel()
					: JSON.parseObject((String) map.get("text"), FlowableFormViewModel.class);
			flowableFormModel.setFlowNodeName((String) map.get("name"));
			flowableFormModel.setProcInstId((String) map.get("id"));
			list.add(flowableFormModel);
		}

		rePackage(list);

		IPage<FlowableFormViewModel> resultData = CkPageQuery.cloneNew(pageData);
		resultData.setRecords(list);
		return resultData;
	}

	@Override
	public IPage<FlowableFormViewModel> findMyCreatedTask(CkPageQuery request) {
		String userId = (String)request.get("userId") ;
		StringBuilder sql = new StringBuilder();
		sql.append("select t1.PROC_INST_ID_ id,t1.START_TIME_,t2.TEXT_ text ");//
		sql.append("from ACT_HI_PROCINST t1,ACT_HI_VARINST t2 ");
		sql.append("where t1.PROC_INST_ID_ = t2.PROC_INST_ID_ and t2.NAME_='formModel' ");
		sql.append("	and exists(select 1 from ACT_HI_IDENTITYLINK t3  ");
		sql.append("		WHERE t1.PROC_INST_ID_ = t3.PROC_INST_ID_ and t3.TYPE_='starter' and USER_ID_='").append(userId).append("') ");
		sql.append("order by t1.START_TIME_ desc");
		// 查询的时候会根据ID_进行组织数据，如果ID_一致，就认为是一条数据

		IPage<Map<String, Object>> pageData = flowableTaskMapper.select(request.getPage(), sql.toString());

		List<FlowableFormViewModel> list = new ArrayList<>();
		for (Map<String, Object> map : pageData.getRecords()) {
			FlowableFormViewModel flowableFormModel = StrUtil.isBlank((String) map.get("text"))
					? new FlowableFormViewModel()
					: JSON.parseObject((String) map.get("text"), FlowableFormViewModel.class);
//			flowableFormModel.setFlowNodeName(task.getName());
			flowableFormModel.setProcInstId((String) map.get("id"));
			list.add(flowableFormModel);
		}

		rePackage(list);

		IPage<FlowableFormViewModel> resultData = CkPageQuery.cloneNew(pageData);
		resultData.setRecords(list);
		return resultData;
	}

	@Override
	public IPage<FlowableFormViewModel> findDoneTask(CkPageQuery request) {
		String userId = (String)request.get("userId") ;
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT id ,time,t2.TEXT_ text ");
		sql.append("FROM (SELECT t1.PROC_INST_ID_ id,max(t1.LAST_UPDATED_TIME_) time ");
		sql.append("FROM ACT_HI_TASKINST t1 ");
		sql.append("WHERE t1.END_TIME_ is not null AND t1.ASSIGNEE_ = '").append(userId).append("' ");
		sql.append("and exists(select 1 from ACT_RU_TASK t3 where t1.PROC_INST_ID_=t3.PROC_INST_ID_) group by id) t1 ");
		sql.append(",ACT_HI_VARINST t2 ");
		sql.append("WHERE t1.id = t2.PROC_INST_ID_ and t2.NAME_='formModel' ");
		sql.append("order by time desc");

		// 查询的时候会根据ID_进行组织数据，如果ID_一致，就认为是一条数据

		IPage<Map<String, Object>> pageData = flowableTaskMapper.select(request.getPage(), sql.toString());

		List<FlowableFormViewModel> list = new ArrayList<>();
		for (Map<String, Object> map : pageData.getRecords()) {
			FlowableFormViewModel flowableFormModel = StrUtil.isBlank((String) map.get("text"))
					? new FlowableFormViewModel()
					: JSON.parseObject((String) map.get("text"), FlowableFormViewModel.class);
//			flowableFormModel.setFlowNodeName(task.getName());
			flowableFormModel.setProcInstId((String) map.get("id"));
			list.add(flowableFormModel);
		}

		rePackage(list);

		list.stream().sorted(Comparator.comparing(FlowableFormModel::getCreatedAt));

		IPage<FlowableFormViewModel> resultData = CkPageQuery.cloneNew(pageData);
		resultData.setRecords(list);

		return resultData;
	}

	@Override
	public IPage<FlowableFormViewModel> findDownAndOverTask(
			CkPageQuery request) {
		String userId = (String)request.get("userId") ;
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT id,time,t2.TEXT_ text ");
		sql.append("FROM (SELECT t1.PROC_INST_ID_ id,max(t1.LAST_UPDATED_TIME_) time ");
		sql.append("FROM ACT_HI_TASKINST t1 ");
		sql.append("WHERE t1.END_TIME_ is not null AND t1.ASSIGNEE_ = '").append(userId).append("' ");
		sql.append(
				"and not exists(select 1 from ACT_RU_TASK t3 where t1.PROC_INST_ID_=t3.PROC_INST_ID_) group by id) t1 ");
		sql.append(",ACT_HI_VARINST t2 ");
		sql.append("WHERE t1.id = t2.PROC_INST_ID_ and t2.NAME_='formModel' ");
		sql.append("order by time desc");
		// 查询的时候会根据ID_进行组织数据，如果ID_一致，就认为是一条数据

		IPage<Map<String, Object>> pageData = flowableTaskMapper.select(request.getPage(), sql.toString());

		List<FlowableFormViewModel> list = new ArrayList<>();
		for (Map<String, Object> map : pageData.getRecords()) {
			FlowableFormViewModel flowableFormModel = StrUtil.isBlank((String) map.get("text"))
					? new FlowableFormViewModel()
					: JSON.parseObject((String) map.get("text"), FlowableFormViewModel.class);
//			flowableFormModel.setFlowNodeName(task.getName());
			flowableFormModel.setProcInstId((String) map.get("id"));
			list.add(flowableFormModel);
		}

		rePackage(list);

		list.stream().sorted(Comparator.comparing(FlowableFormModel::getCreatedAt));

		IPage<FlowableFormViewModel> resultData = CkPageQuery.cloneNew(pageData);
		resultData.setRecords(list);

		return resultData;
	}

	@Override
	public IPage<FlowableFormViewModel> findRrejectTask(CkPageQuery request) {
		String userId = (String)request.get("userId") ;
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT PROC_INST_ID_ id,LAST_UPDATED_TIME_,TEXT_ text  ");
		sql.append("FROM ACT_HI_VARINST t1 where NAME_='formModel' and PROC_INST_ID_ in( ");
		sql.append("select distinct PROC_INST_ID_ from ACT_HI_VARINST t2 ");
		sql.append("where t2.NAME_='audit' and t2.TEXT_='reject' ");
		sql.append("and exists(select 1 from ACT_HI_IDENTITYLINK t3 ");
		sql.append("where t2.TASK_ID_=t3.TASK_ID_ and USER_ID_='").append(userId).append("')) ");
		sql.append("ORDER BY LAST_UPDATED_TIME_ DESC ");
		// 查询的时候会根据ID_进行组织数据，如果ID_一致，就认为是一条数据

		IPage<Map<String, Object>> pageData = flowableTaskMapper.select(request.getPage(), sql.toString());

		List<FlowableFormViewModel> list = new ArrayList<>();
		for (Map<String, Object> map : pageData.getRecords()) {
			FlowableFormViewModel flowableFormModel = StrUtil.isBlank((String) map.get("text"))
					? new FlowableFormViewModel()
					: JSON.parseObject((String) map.get("text"), FlowableFormViewModel.class);
//			flowableFormModel.setFlowNodeName(task.getName());
			flowableFormModel.setProcInstId((String) map.get("id"));
			list.add(flowableFormModel);
		}

		rePackage(list);

		list.stream().sorted(Comparator.comparing(FlowableFormModel::getCreatedAt));

		IPage<FlowableFormViewModel> resultData = CkPageQuery.cloneNew(pageData);
		resultData.setRecords(list);

		return resultData;
	}

	private void rePackage(List<FlowableFormViewModel> list) {
		DataBuilder.of(list).appendBuilder(new UserDataBuilder(), new DataBuildConfig("createdBy", "createdByName"))
				.appendBuilder(new DeptDataBuilder(), new DataBuildConfig("deptId", "deptName")).build();
	}
	
	@Override
	public byte[] generateImageByBusinessKey(String businessKey) throws IOException {
		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
				.processInstanceBusinessKey(businessKey).singleResult();

		// 流程走完的不显示图
		if (processInstance == null) {
			return null;
		}

		return imageService.generateImageByProcInstId(processInstance.getId());
	}

//	@Override
//	public byte[] generateImageByBusinessKey(String businessKey) throws IOException {
//		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
//				.processInstanceBusinessKey(businessKey).singleResult();
//
//		// 流程走完的不显示图
//		if (processInstance == null) {
//			return null;
//		}
//
//		// 使用流程实例ID，查询正在执行的执行对象表，返回流程实例对象
//		List<Execution> executions = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId())
//				.list();
//
//		// 得到正在执行的Activity的Id
//		List<String> activityIds = new ArrayList<>();
//		for (Execution exe : executions) {
//			List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
//			activityIds.addAll(ids);
//		}
//
//		// 获取流程图
//		BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
//		ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
//		ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
//		
//		byte[] data = null;
//		try (InputStream in = diagramGenerator.generateDiagram(bpmnModel, "bmp", activityIds, Collections.emptyList(),
//				engconf.getActivityFontName(), engconf.getLabelFontName(), engconf.getAnnotationFontName(),  engconf.getClassLoader(), 1.0,
//				true)) {
//			data = IOUtils.toByteArray(in);
//		}
//
//		return data;
//	}

	@Override
	public void deleteProcessInstance(String businessKey) {
		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
				.processInstanceBusinessKey(businessKey).singleResult();

		if (processInstance != null) {
			runtimeService.deleteProcessInstance(processInstance.getId(), "单据删除");
			historyService.deleteHistoricProcessInstance(processInstance.getId());
		} else {
			HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
					.processInstanceBusinessKey(businessKey).singleResult();

			if (historicProcessInstance == null) {
				throw new ChuangkeException(String.format("未找到[%s]的流程信息", businessKey));
			}

			historyService.deleteHistoricProcessInstance(historicProcessInstance.getId());

		}

	}

}
